package com.bandit.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author Bandit
 * @create 2022/2/23 23:56
 */
@Slf4j
public class PropertiesFileUtil {
    private PropertiesFileUtil(){

    }

    public static Properties readPropertiesFile(String fileName){
        URL url = Thread.currentThread().getContextClassLoader().getResource("");
        String rpcConfigPath = "";
        if (url != null) {//getResource如果路径出现中文就会转义，导致rpc.properties无法正常读取，直接抛出异常
            String decode = null;
            try {
                decode = URLDecoder.decode(url.getPath(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            rpcConfigPath = decode + fileName;
        }
        Properties properties = null;
        try (InputStreamReader inputStreamReader = new InputStreamReader(
                new FileInputStream(rpcConfigPath), StandardCharsets.UTF_8)) {
            properties = new Properties();
            properties.load(inputStreamReader);
        } catch (IOException e) {
            log.error("occur exception when read properties file [{}]", fileName);
        }
        return properties;
    }
}
